import 'dart:convert';

class Note {
  final String id;       
  final String title;   
  final String content; 
  final DateTime createdAt; 
  final DateTime updatedAt; 
  final bool isPinned;    
  final String? folderId; 
  final String? password; 
  final String? label; 
  final List<String> imagePaths; 
  final List<String> audioPaths; 

  Note({
    required this.id,
    required this.title,
    required this.content,
    required this.createdAt,
    required this.updatedAt,
    this.isPinned = false,
    this.folderId,
    this.password,
    this.label,
    this.imagePaths = const [],
    this.audioPaths = const [],
  });

  Note copyWith({
    String? id,
    String? title,
    String? content,
    DateTime? createdAt,
    DateTime? updatedAt,
    bool? isPinned,
    String? folderId,
    String? password,
    String? label,
    List<String>? imagePaths,
    List<String>? audioPaths,
  }) {
    return Note(
      id: id ?? this.id,
      title: title ?? this.title,
      content: content ?? this.content,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      isPinned: isPinned ?? this.isPinned,
      folderId: folderId ?? this.folderId,
      password: password ?? this.password,
      label: label ?? this.label,
      imagePaths: imagePaths ?? this.imagePaths,
      audioPaths: audioPaths ?? this.audioPaths,
    );
  }

  factory Note.fromMap(Map<String, dynamic> map) {
    return Note(
      id: map['id'],
      title: map['title'],
      content: map['content'],
      createdAt: DateTime.parse(map['created_at']),
      updatedAt: DateTime.parse(map['updated_at']),
      isPinned: map['is_pinned'] == 1,
      folderId: map['folder_id'],
      password: map['password'],
      label: map['label'],
      imagePaths: _parseJsonString(map['image_paths']),
      audioPaths: _parseJsonString(map['audio_paths']),
    );
  }

  static List<String> _parseJsonString(String? jsonString) {
    if (jsonString == null || jsonString.isEmpty) return [];
    try {
      final List<dynamic> list = json.decode(jsonString);
      return list.map((e) => e.toString()).toList();
    } catch (e) {
      return [];
    }
  }
}